package com.mtiiot.fsmanage.server;


import com.mtiiot.fsmanage.utils.Contants;
import com.mtiiot.fsmanage.utils.FsViewConfig;
import com.mtiiot.fscore.bean.MetadataInfo;
import com.mtiiot.fscore.inter1.RedisService1;
import com.mtiiot.fscore.utils.StringUtil;
import com.mtiiot.fsmanage.bean.parameter.Sys;
import com.mtiiot.fsmanage.core.dao.BaseElasticsearch;
import org.codehaus.jackson.map.ObjectMapper;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;


@Service
@Transactional
public class SysServer {
    private static String INDEX = Contants.INDEX_PARAMETER;
    private static String TYPE = Contants.TYPE_PARAMETER_SYSTEM;
    @Autowired
    private BaseElasticsearch baseElasticsearch;
    @Autowired
    private RedisService1 redisService1;

    @Autowired
    private FsViewConfig fsViewConfig;

    public boolean validateSysName(String sysName)throws Exception{
        Client client=null;
        try{
            client=baseElasticsearch.getEsDataSource().getClient();
            SearchRequestBuilder srb = client.prepareSearch(INDEX)
                    .setTypes(TYPE)
                    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                    .setExplain(true);
            // 最后就是返回搜索响应信息
                srb.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("sysName", sysName)));
            SearchResponse response =srb.execute().actionGet();
            SearchHits searchHits = response.getHits();
            SearchHit[] hits = searchHits.getHits();
            if(hits.length==0){
                return false;
            }else{
                return true;
            }
        }finally {
            if(client!=null){
                try {
                    baseElasticsearch.getEsDataSource().releaseClient(client);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public boolean validateSysId(String sysId)throws Exception{
        Client client=null;
        try{
            client=baseElasticsearch.getEsDataSource().getClient();
            SearchRequestBuilder srb = client.prepareSearch(INDEX)
                    .setTypes(TYPE)
                    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                    .setExplain(true);
            // 最后就是返回搜索响应信息
            srb.setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("id", sysId)));
            SearchResponse response =srb.execute().actionGet();
            SearchHits searchHits = response.getHits();
            SearchHit[] hits = searchHits.getHits();
            if(hits.length==0){
                return false;
            }else{
                return true;
            }
        }finally {
            if(client!=null){
                try {
                    baseElasticsearch.getEsDataSource().releaseClient(client);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    /**
     *
     * @param keyWord
     * @return
     */
    public List<Sys> querySys(String keyWord)throws Exception{
        Client client=null;
        try{
            client=baseElasticsearch.getEsDataSource().getClient();
            SearchRequestBuilder srb = client.prepareSearch(INDEX)
                    .setTypes(TYPE)
                    .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                    .setExplain(true);
            // 最后就是返回搜索响应信息
            if(!StringUtil.isEmpty(keyWord)){
                //srb.setQuery(QueryBuilders.simpleQueryStringQuery(keyWord));
                srb.setQuery(QueryBuilders.queryStringQuery(keyWord));
            }
            SearchResponse response =srb.execute().actionGet();
            SearchHits searchHits = response.getHits();
            SearchHit[] hits = searchHits.getHits();
            List<Sys> ss=new ArrayList<Sys>();
            if(hits.length==0){
                return ss;
            }
            for(SearchHit hit:hits){
                Map<String, Object> sm=hit.sourceAsMap();
                Sys s=new Sys();
                s.setId(sm.get("id").toString());
                s.setSysName(sm.get("sysName").toString());
                s.setDesc(sm.get("desc").toString());
                ss.add(s);
            }
            return ss;
        }finally {
            if(client!=null){
                try {
                    baseElasticsearch.getEsDataSource().releaseClient(client);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     *
     * @param id
     * @return
     */
    public boolean deleteSys(String id)throws Exception{
         redisService1.hdel(new MetadataInfo(fsViewConfig.getFsviewSysId()),fsViewConfig.getSysRedisKey(), id);
         return baseElasticsearch.deleteIndex(INDEX,TYPE,id);
    }

    /**
     *批量删除
     * @param ids
     * @return
     */
    public boolean deleteSyss(String ids)throws Exception{
         redisService1.hdel(new MetadataInfo(fsViewConfig.getFsviewSysId()),fsViewConfig.getSysRedisKey(),ids.split(","));
         return baseElasticsearch.deleteIndexs(INDEX,TYPE,ids);
    }

    /**
     *
     * @param
     * @return
     */
    public boolean addSys(String sysName,String desc,String sysId)throws Exception{
            Sys s=new Sys();
            String uuid="";
            if(!StringUtil.isEmpty(sysId)){
                uuid=sysId;
            }else{
                uuid=UUID.randomUUID().toString().replaceAll("-", "");
            }
            s.setId(uuid);
            s.setSysName(sysName);
            s.setDesc(desc);
            Date date=new Date();
            s.setTime(date);
            s.setUpdateTime(date);
            ObjectMapper mapper = new ObjectMapper();
            String jsonStr=mapper.writeValueAsString(s);
            redisService1.hset(new MetadataInfo(fsViewConfig.getFsviewSysId()),fsViewConfig.getSysRedisKey(),uuid,sysName);
            return baseElasticsearch.createIndexById(INDEX,TYPE,jsonStr,uuid);
    }

    /**
     *
     * @param
     * @return
     */
    public boolean updateSys(String id,String sysName,String desc)throws Exception{
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("sysName",sysName);
            map.put("desc",desc);
            map.put("updateTime",new Date().getTime());
            redisService1.hset(new MetadataInfo(fsViewConfig.getFsviewSysId()),fsViewConfig.getSysRedisKey(),id,sysName);
            return baseElasticsearch.updateIndex(INDEX,TYPE,id,map);
    }
}
